#include <thread>

#include "bindings/bindings_init.h"
#include "helpers/font_helper.h"
#include "helpers/general.h"
#include "helpers/resource.h"
#include "models/dimensions_helper.h"
#include "refs.h"

namespace ohos_rive {
napi_value RiveCppCalculateRequiredBounds(napi_env env, napi_callback_info info)
{
    napi_value result;
    napi_get_undefined(env, &result);

    napi_status status;
    size_t argc = 6;
    napi_value args[6] = {nullptr};
    status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
    if (status != napi_ok || argc < 6) {
        LOGE("Failed to parse arguments for RiveCppCalculateRequiredBounds");
        return result;
    }

    rive::Fit fit = GetFit(env, args[0]);
    rive::Alignment alignment = GetAlignment(env, args[1]);
    rive::AABB availableBounds = RectFToAABB(env, args[2]);
    rive::AABB artboardBounds = RectFToAABB(env, args[3]);

    double scaleFactor = 0.0f;
    status = napi_get_value_double(env, args[5], &scaleFactor);
    if (status != napi_ok) {
        LOGE("Failed to parse scaleFactor for RiveCppCalculateRequiredBounds");
        return result;
    }

    DimensionsHelper helper;
    auto required = helper.computeDimensions(fit, alignment, availableBounds, artboardBounds, scaleFactor);
    AABBToRectF(env, required, args[4]);

    return result;
}

napi_value RiveCppInitialize(napi_env env, napi_callback_info info)
{
#if defined(DEBUG) || defined(LOG)
    std::thread t(LogThread);
    t.detach();
#endif
    SetSystemVersion();
    rive::Font::gFallbackProc = FontHelper::FindFontFallback;
    return nullptr;
}

napi_value RiveCppRegisterClass(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value args[2] = {nullptr};
    napi_status status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
    if (status != napi_ok || argc < 1) {
        LOGE("Failed to parse arguments for RegisterClass");
        return nullptr;
    }

    RegisterClass(env, args, argc);

    napi_value result;
    napi_get_undefined(env, &result);
    return result;
}

napi_value RiveCppUnregisterClass(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value args[2] = {nullptr};
    napi_status status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
    if (status != napi_ok || argc < 1) {
        LOGE("Failed to parse arguments for UnregisterClass");
        return nullptr;
    }

    UnregisterClass(env, args, argc);

    napi_value result;
    napi_get_undefined(env, &result);
    return result;
}
} // namespace ohos_rive